package com.web.config;

import com.web.currency.entity.Currency;
import com.web.currency.service.CurrencyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component  //此类一定要交给spring管理
public class ConsumerRunner implements ApplicationRunner{

	private final static Logger logger = LoggerFactory.getLogger(ConsumerRunner.class);

	public static Map<String, Object> currencyMap = new HashMap<String, Object>();

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private CurrencyService currencyService;

	@Override
	public void run(ApplicationArguments args) throws Exception{
		logger.info("开始加载Currency数据到redis中......");
		// 从数据库获取数据
		List<Currency> currencyList = currencyService.getCurrencyList();

		// 使用stream流将list集合转成map集合
		currencyMap = currencyList.stream().collect(Collectors.toMap(key-> key.getCurrency(), value -> value.getCurrency()));

		currencyMap.forEach((k, v) -> System.out.println(k + " ==> " + v));
		// 将货币数据存入Redis
		redisTemplate.opsForHash().putAll("currencyMap",currencyMap);
	}
}
